<template>
    <el-container class="app-container">
        <el-main class="main-content">
            <div class="start-view">
                <!-- 左侧创建按钮区域 -->
                <div class="left-section">
                    <div class="btn-group">
                        <!-- 创建知识库按钮和表单 -->
                        <el-popover :width="300" trigger="hover" :show-arrow="true" transition="el-fade-in-linear"
                            popper-class="create-popover">
                            <template #reference>
                                <div class="square-button">
                                    <el-button type="primary" size="large" :icon="FolderAdd" class="action-btn">
                                        <div class="btn-content">
                                            <el-icon class="custom-icon">
                                                <FolderAdd />
                                            </el-icon>
                                            <span>大大知识库</span>
                                        </div>
                                    </el-button>
                                </div>
                            </template>
                            <template #default>
                                <div class="create-form">
                                    <h3>创建知识库</h3>
                                    <el-form :model="repoForm" label-position="top">
                                        <el-form-item label="知识库名称">
                                            <el-input v-model="repoForm.name" placeholder="请输入知识库名称" />
                                        </el-form-item>
                                        <el-form-item label="描述">
                                            <el-input v-model="repoForm.description" type="textarea" :rows="3"
                                                placeholder="请输入知识库描述（选填）" />
                                        </el-form-item>
                                        <el-form-item>
                                            <el-button type="primary" @click="createRepo" :disabled="!repoForm.name">
                                                创建
                                            </el-button>
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </template>
                        </el-popover>

                        <!-- 创建随记按钮和表单 -->
                        <el-popover :width="300" trigger="hover" :show-arrow="true" transition="el-fade-in-linear"
                            popper-class="create-popover">
                            <template #reference>
                                <div class="square-button">
                                    <el-button type="success" size="large" :icon="DocumentAdd" class="action-btn">
                                        <div class="btn-content">
                                            <el-icon class="custom-icon">
                                                <DocumentAdd />
                                            </el-icon>
                                            <span>小小随记</span>
                                        </div>
                                    </el-button>
                                </div>
                            </template>
                            <template #default>
                                <div class="create-form">
                                    <h3>创建随记</h3>
                                    <el-form :model="docForm" label-position="top">
                                        <el-form-item label="随记名称">
                                            <el-input v-model="docForm.name" placeholder="请输入随记名称" />
                                        </el-form-item>
                                        <el-form-item>
                                            <el-button type="success" @click="createDoc" :disabled="!docForm.name">
                                                创建
                                            </el-button>
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </template>
                        </el-popover>
                    </div>
                </div>

                <!-- 右侧列表区域 -->
                <div class="right-section">
                    <!-- 知识库列表 -->
                    <div class="list-section">
                        <h3>我的知识库</h3>
                        <el-scrollbar height="200px">
                            <el-empty v-if="repositories.length === 0" description="暂无知识库" />
                            <ul v-else class="item-list">
                                <li v-for="repo in repositories" :key="repo.id" class="list-item">
                                    <div class="item-content" @click="router.push(`/repository/${repo.id}`)">
                                        <el-icon>
                                            <Folder />
                                        </el-icon>
                                        <span>{{ repo.name }}</span>
                                    </div>
                                    <div class="item-actions">
                                        <el-button type="danger" text @click.stop="deleteRepo(repo.id)"
                                            :icon="Delete" />
                                    </div>
                                </li>
                            </ul>
                        </el-scrollbar>
                    </div>

                    <!-- 随记列表 -->
                    <div class="list-section">
                        <h3>我的随记</h3>
                        <el-scrollbar height="300px">
                            <el-empty v-if="notes.length === 0" description="暂无随记" />
                            <ul v-else class="item-list">
                                <li v-for="note in notes" :key="note.id" class="list-item">
                                    <div class="item-content" @click="router.push(`/file/${note.id}`)">
                                        <el-icon>
                                            <Document />
                                        </el-icon>
                                        <span>{{ note.title }}</span>
                                    </div>
                                    <div class="item-actions">
                                        <el-dropdown trigger="click"
                                            @command="(command) => handleNoteCommand(command, note.id)">
                                            <el-button text>
                                                <el-icon>
                                                    <More />
                                                </el-icon>
                                            </el-button>
                                            <template #dropdown>
                                                <el-dropdown-menu>
                                                    <el-dropdown-item command="addToRepo">添加到知识库</el-dropdown-item>
                                                    <el-dropdown-item divided command="delete">删除</el-dropdown-item>
                                                </el-dropdown-menu>
                                            </template>
                                        </el-dropdown>
                                    </div>
                                </li>
                            </ul>
                        </el-scrollbar>
                    </div>
                </div>
            </div>
        </el-main>
    </el-container>
</template>

<script setup>
// import NavBar from '@/components/NavBar.vue'
import {
    FolderAdd,
    DocumentAdd,
    Folder,
    Document,
    Delete,
    More
} from '@element-plus/icons-vue'
import { ref, onMounted, h } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const router = useRouter()
const baseURL = 'http://127.0.0.1:3000'

const repoForm = ref({
    name: '',
    description: ''
})

const docForm = ref({
    name: ''
})

// 状态变量
const repositories = ref([])
const notes = ref([])
const selectedRepo = ref(null)

// 获取知识库列表
const fetchRepositories = async () => {
    try {
        const response = await fetch(`${baseURL}/api/repositories`, {
            headers: {
                Authorization: 'Bearer ' + userStore.token,
            }
        })
        if (!response.ok) throw new Error('获取知识库列表失败')
        repositories.value = await response.json()
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 获取随记列表
const fetchNotes = async () => {
    try {
        const response = await fetch(`${baseURL}/api/notes`, {
            headers: {
                Authorization: 'Bearer ' + userStore.token,
            }
        })
        if (!response.ok) throw new Error('获取随记列表失败')
        notes.value = await response.json()
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 创建知识库
const createRepo = async () => {
    try {
        const response = await fetch(`${baseURL}/api/repositories`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + userStore.token
            },
            body: JSON.stringify({
                name: repoForm.value.name,
                description: repoForm.value.description
            })
        })

        if (!response.ok) throw new Error('创建知识库失败')

        const newRepo = await response.json()
        repositories.value.push(newRepo)
        ElMessage.success('创建知识库成功')
        repoForm.value.name = ''

        // 跳转到知识库页面
        router.push(`/repository/${newRepo.id}`)
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 创建随记
const createDoc = async () => {
    try {
        const response = await fetch(`${baseURL}/api/notes/documents`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + userStore.token
            },
            body: JSON.stringify({
                title: docForm.value.name,
                content: '',
            })
        })

        if (!response.ok) throw new Error('创建随记失败')

        const newNote = await response.json()
        notes.value.push(newNote)
        ElMessage.success('创建随记成功')
        docForm.value.name = ''

        // 跳转到编辑器页面
        router.push(`/file/${newNote.id}`)
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 删除知识库
const deleteRepo = async (id) => {
    try {
        const response = await fetch(`${baseURL}/api/repositories/${id}`, {
            method: 'DELETE',
            headers: {
                Authorization: 'Bearer ' + userStore.token,
            }
        })

        if (!response.ok) throw new Error('删除知识库失败')

        repositories.value = repositories.value.filter(repo => repo.id !== id)
        ElMessage.success('删除知识库成功')
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 删除随记
const deleteNote = async (id) => {
    try {
        const response = await fetch(`${baseURL}/api/notes/${id}`, {
            method: 'DELETE',
            headers: {
                Authorization: 'Bearer ' + userStore.token,
            }
        })

        if (!response.ok) throw new Error('删除随记失败')

        notes.value = notes.value.filter(note => note.id !== id)
        ElMessage.success('删除随记成功')
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 添加随记到知识库
const addNoteToRepo = async (noteId, repoId) => {
    try {
        const response = await fetch(`${baseURL}/api/notes/${noteId}/repository`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + userStore.token
            },
            body: JSON.stringify({ repositoryId: repoId })
        })

        if (!response.ok) throw new Error('添加到知识库失败')

        ElMessage.success('添加到知识库成功')
        await fetchNotes() // 刷新笔记列表
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 处理随记操作
const handleNoteCommand = async (command, noteId) => {
    switch (command) {
        case 'addToRepo':
            await showAddToRepoDialog(noteId)
            break
        case 'delete':
            await deleteNote(noteId)
            break
    }
}

// 显示添加到知识库的对话框
const showAddToRepoDialog = async (noteId) => {
    try {
        // 如果只有一个知识库，直接设置为默认选择
        if (repositories.value.length === 1) {
            selectedRepo.value = repositories.value[0].id;
        }
        
        await ElMessageBox.confirm(
            h('div', { style: 'margin-bottom: 10px' }, [
                h('p', '选择要添加到的知识库：'),
                h(
                    'select',
                    {
                        style: 'width: 100%; padding: 5px;',
                        value: selectedRepo.value || '',
                        onChange: (event) => {
                            selectedRepo.value = parseInt(event.target.value)
                        }
                    },
                    repositories.value.map(repo =>
                        h('option', { value: repo.id }, repo.name)
                    )
                )
            ]),
            '添加到知识库',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal: false
            }
        )

        if (selectedRepo.value) {
            await addNoteToRepo(noteId, selectedRepo.value)
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message)
        }
    }
}

// 初始化时获取列表
onMounted(() => {
    fetchRepositories()
    fetchNotes()
})
</script>

<style scoped>
.app-container {
    min-height: 100vh;
    display: flex;
}

.main-content {
    flex: 1;
    margin-left: 200px;
    background: #f7f8fa;
    min-height: 100vh;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.start-view {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.btn-group {
    display: flex;
    flex-direction: row;
    gap: 48px;
    align-items: center;
}

.square-button {
    .action-btn {
        width: 180px;
        height: 180px;
        border-radius: 8px;
        padding: 0;
        transition: all 0.3s ease;

        &:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        }
    }
}

.btn-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;

    .custom-icon {
        font-size: 48px;
        margin-bottom: 16px;
    }

    span {
        font-size: 1.2rem;
        font-weight: 500;
    }
}

.start-view {
    display: flex;
    padding: 40px;
    gap: 40px;
}

.left-section {
    flex: 1;
    display: flex;
    justify-content: center;
}

.right-section {
    width: 300px;
    display: flex;
    flex-direction: column;
    gap: 30px;
}

.list-section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    h3 {
        margin: 0 0 16px;
        color: #303133;
        font-size: 16px;
    }
}

.item-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.list-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    border-radius: 4px;
    transition: all 0.3s;
    cursor: pointer;

    &:hover {
        background: #f5f7fa;
    }

    .item-content {
        display: flex;
        align-items: center;
        gap: 8px;
        flex: 1;

        .el-icon {
            font-size: 16px;
            color: #909399;
        }

        span {
            color: #606266;
        }
    }

    .item-actions {
        display: flex;
        gap: 4px;
        opacity: 0;
        transition: opacity 0.3s;
    }

    &:hover .item-actions {
        opacity: 1;
    }
}

.create-form {
    padding: 10px;

    h3 {
        margin: 0 0 20px;
        font-size: 16px;
        color: #333;
    }
}

:deep(.create-popover) {
    padding: 20px;

    .el-form-item__label {
        font-weight: 500;
    }

    .el-button {
        width: 100%;
        margin-top: 10px;
    }
}
</style>
